<template>
  <view class="h5-login">
    <view class="login-form">
      <view class="form-title">手机号登录</view>
      
      <!-- 手机号输入 -->
      <view class="input-group">
        <view class="input-label">手机号</view>
        <input 
          class="form-input" 
          type="tel" 
          placeholder="请输入手机号" 
          v-model="formData.phone"
          maxlength="11"
          @input="onPhoneInput"
        />
        <view class="input-error" v-if="errors.phone">{{ errors.phone }}</view>
      </view>
      
      <!-- 验证码输入 -->
      <view class="input-group">
        <view class="input-label">验证码</view>
        <view class="code-input-row">
          <input 
            class="form-input code-input" 
            type="number" 
            placeholder="请输入验证码" 
            v-model="formData.code"
            maxlength="6"
            @input="onCodeInput"
          />
          <button 
            class="send-code-btn" 
            @click="sendCode"
            :disabled="!canSendCode || sendingCode"
            :class="{ 'disabled': !canSendCode || sendingCode }"
          >
            {{ codeButtonText }}
          </button>
        </view>
        <view class="input-error" v-if="errors.code">{{ errors.code }}</view>
      </view>
      
      <!-- 登录按钮 -->
      <button 
        class="login-btn" 
        @click="handleLogin"
        :disabled="!canLogin || logging"
        :class="{ 'disabled': !canLogin || logging }"
      >
        {{ logging ? '登录中...' : '登录' }}
      </button>
      
      <!-- 用户协议 -->
      <view class="agreement">
        <checkbox-group @change="onAgreementChange">
          <label class="agreement-item">
            <checkbox :checked="agreed" />
            <text class="agreement-text">
              我已阅读并同意
              <text class="link" @click="showUserAgreement">《用户协议》</text>
              和
              <text class="link" @click="showPrivacyPolicy">《隐私政策》</text>
            </text>
          </label>
        </checkbox-group>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'H5Login',
  data() {
    return {
      formData: {
        phone: '',
        code: ''
      },
      errors: {
        phone: '',
        code: ''
      },
      countdown: 0,
      sendingCode: false,
      logging: false,
      agreed: false
    }
  },
  
  computed: {
    // 是否可以发送验证码
    canSendCode() {
      return this.isValidPhone(this.formData.phone) && this.countdown === 0
    },
    
    // 验证码按钮文本
    codeButtonText() {
      if (this.sendingCode) return '发送中...'
      if (this.countdown > 0) return `${this.countdown}s`
      return '发送验证码'
    },
    
    // 是否可以登录
    canLogin() {
      return this.isValidPhone(this.formData.phone) && 
             this.formData.code.length === 6 && 
             this.agreed
    }
  },
  
  methods: {
    // 手机号输入处理
    onPhoneInput() {
      this.errors.phone = ''
      if (this.formData.phone && !this.isValidPhone(this.formData.phone)) {
        this.errors.phone = '手机号格式不正确'
      }
    },
    
    // 验证码输入处理
    onCodeInput() {
      this.errors.code = ''
      if (this.formData.code && !/^\d{1,6}$/.test(this.formData.code)) {
        this.formData.code = this.formData.code.replace(/\D/g, '').slice(0, 6)
      }
    },
    
    // 协议勾选处理
    onAgreementChange(e) {
      this.agreed = e.detail.value.length > 0
    },
    
    // 验证手机号格式
    isValidPhone(phone) {
      return /^1[3-9]\d{9}$/.test(phone)
    },
    
    // 发送验证码
    async sendCode() {
      if (!this.canSendCode) return
      
      try {
        this.sendingCode = true
        this.errors.phone = ''
        
        await this.$store.dispatch('auth/sendSmsCode', this.formData.phone)
        
        uni.showToast({
          title: '验证码已发送',
          icon: 'success'
        })
        
        this.startCountdown()
      } catch (error) {
        console.error('发送验证码失败:', error)
        this.errors.phone = error.message || '发送失败，请重试'
        
        uni.showToast({
          title: error.message || '发送失败',
          icon: 'none'
        })
      } finally {
        this.sendingCode = false
      }
    },
    
    // 开始倒计时
    startCountdown() {
      this.countdown = 60
      const timer = setInterval(() => {
        this.countdown--
        if (this.countdown <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    },
    
    // 处理登录
    async handleLogin() {
      if (!this.canLogin) return
      
      // 清除错误信息
      this.errors = { phone: '', code: '' }
      
      // 表单验证
      if (!this.isValidPhone(this.formData.phone)) {
        this.errors.phone = '请输入正确的手机号'
        return
      }
      
      if (!this.formData.code || this.formData.code.length !== 6) {
        this.errors.code = '请输入6位验证码'
        return
      }
      
      if (!this.agreed) {
        uni.showToast({
          title: '请先同意用户协议',
          icon: 'none'
        })
        return
      }
      
      try {
        this.logging = true
        
        await this.$store.dispatch('auth/smsLogin', {
          phone: this.formData.phone,
          code: this.formData.code
        })
        
        uni.showToast({
          title: '登录成功',
          icon: 'success'
        })
        
        // 登录成功，触发事件
        this.$emit('login-success')
        
        // 延迟跳转，让用户看到成功提示
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/index/index'
          })
        }, 1500)
        
      } catch (error) {
        console.error('登录失败:', error)
        
        // 根据错误类型设置错误信息
        if (error.message.includes('验证码')) {
          this.errors.code = error.message
        } else if (error.message.includes('手机号')) {
          this.errors.phone = error.message
        } else {
          uni.showToast({
            title: error.message || '登录失败',
            icon: 'none'
          })
        }
      } finally {
        this.logging = false
      }
    },
    
    // 显示用户协议
    showUserAgreement() {
      uni.navigateTo({
        url: '/pages/legal/user-agreement'
      })
    },
    
    // 显示隐私政策
    showPrivacyPolicy() {
      uni.navigateTo({
        url: '/pages/legal/privacy-policy'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.h5-login {
  padding: 40rpx;
}

.login-form {
  background: white;
  border-radius: 20rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.form-title {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
  text-align: center;
  margin-bottom: 60rpx;
}

.input-group {
  margin-bottom: 40rpx;
}

.input-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 16rpx;
}

.form-input {
  width: 100%;
  height: 88rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 12rpx;
  padding: 0 24rpx;
  font-size: 32rpx;
  color: #333;
  box-sizing: border-box;
  
  &:focus {
    border-color: #007aff;
  }
  
  &::placeholder {
    color: #999;
  }
}

.code-input-row {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.code-input {
  flex: 1;
}

.send-code-btn {
  width: 200rpx;
  height: 88rpx;
  background: linear-gradient(135deg, #007aff, #5ac8fa);
  color: white;
  border: none;
  border-radius: 12rpx;
  font-size: 24rpx;
  font-weight: 500;
  
  &.disabled {
    background: #f5f5f5;
    color: #999;
  }
}

.input-error {
  font-size: 24rpx;
  color: #ff3b30;
  margin-top: 8rpx;
}

.login-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #007aff, #5ac8fa);
  color: white;
  border: none;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: 500;
  margin-top: 40rpx;
  
  &.disabled {
    background: #f5f5f5;
    color: #999;
  }
}

.agreement {
  margin-top: 40rpx;
  padding: 0 20rpx;
}

.agreement-item {
  display: flex;
  align-items: flex-start;
  font-size: 24rpx;
  color: #666;
  line-height: 1.5;
}

.agreement-text {
  margin-left: 16rpx;
  flex: 1;
}

.link {
  color: #007aff;
  text-decoration: underline;
}
</style>